<template>
  <div class="app-container">
    <el-row>
      <!-- 搜索区域 -->
      <el-card style="margin:0 0 5px 5px" v-show="showSearch">
        <el-form ref="queryForm" :inline="true" :model="queryData">
          <el-form-item label="栏目" prop="Q_channel_S_EQ">
            <el-select v-model="queryData.Q_channel_S_EQ" placeholder="栏目">
              <el-option label="全部" value="" />
              <el-option
                v-for="item in optionOfChannel"
                :key="item.dictCode"
                :label="item.dictLabel"
                :value="item.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="标题" prop="Q_title_S_LK">
            <el-input v-model="queryData.Q_title_S_LK" placeholder="标题" />
          </el-form-item>
          <el-form-item label="权限" prop="Q_open_S_EQ">
            <el-select v-model="queryData.Q_open_S_EQ" placeholder="阅读权限">
              <el-option label="全部" value="" />
              <el-option
                v-for="item in optionOfPermission"
                :key="item.dictCode"
                :label="item.dictLabel"
                :value="item.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="Q_status_S_EQ">
            <el-select v-model="queryData.Q_status_S_EQ" placeholder="状态">
              <el-option label="状态" value="" />
              <el-option
                v-for="item in optionOfStatus"
                :key="item.dictCode"
                :label="item.dictLabel"
                :value="item.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item class="fr p-r-10">
            <el-button class="filter-item" type="primary" round icon="el-icon-search" @click="handleFilter">
              搜索
            </el-button>
            <el-button class="filter-item m-l-10" type="info" round icon="el-icon-refresh" @click="handleClear">
              清空
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- table区域 -->
      <el-card class="m-l-5">
        <el-row :gutter="10" class="m-b-5">
          <el-col :span="1.5">
            <el-button v-permission="['spider:crawl:grep']" size="mini" plain type="success" icon="el-icon-plus" @click="handleGrep()">
              抓取
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-permission="['blog:article:public']" v-if="selectionData.length > 0" size="mini" plain type="primary" icon="el-icon-sell" @click="handlePublish()">
              批量发布
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-permission="['blog:article:delete']" v-if="selectionData.length > 0" size="mini" plain type="danger" icon="el-icon-delete" @click="handleDelete()">
              删除
            </el-button>
          </el-col>
          <table-toolbar :showSearch.sync="showSearch" @refresh="getTableData" />
        </el-row>
        <el-table
          ref="queryTable"
          v-loading="tableLoading"
          row-key="articleId"
          :data="tableData"
          element-loading-text="加载中"
          border
          fit
          highlight-current-row
          show-overflow-tooltip
          height="100px"
          v-el-height-adaptive-table="{bottomOffset: 110}"
          @sort-change="sortChange"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="40" />
          <el-table-column align="center" label="标题" prop="title" sortable show-overflow-tooltip />
          <el-table-column align="center" label="栏目" prop="channel" sortable width="120">
            <template slot-scope="scope">
              <el-tag :type="getDictType('channel', scope.row.channel)" v-text="getDictValue('channel', scope.row.channel)" />
            </template>
          </el-table-column>
          <el-table-column align="center" label="缩略图" width="120">
            <template slot-scope="scope">
              <el-avatar shape="square" fit="fill" :src="getImageSrc(scope.row.thumbnail)" />
            </template>
          </el-table-column>
          <el-table-column align="center" label="推荐" prop="featured" sortable width="90">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.featured"
                active-value="0"
                inactive-value="1"
                :disabled="!changePerm"
                @change="feature(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column align="center" label="状态" sortable width="90">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="light" :content="getDictValue('status', scope.row.status)" placement="top">
                <el-link :type="getDictColor('status', scope.row.status + '')" :underline="false"><i :class="'el-icon-'+getDictType('status', scope.row.status + '')"></i></el-link>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="200" fixed="right">
            <template slot-scope="scope">
              <el-dropdown>
                <el-link v-permission="['spider:crawl:grep']" class="m-r-10" type="primary" icon="el-icon-view" @click="handleEdit(scope.row.articleId)">查看</el-link>
                <el-link v-permission="['blog:article:delete']" class="m-r-10" type="danger" icon="el-icon-delete" @click="handleDelete(scope.row.articleId)">删除</el-link>
                <span class="el-dropdown-link" style="font-size: smaller">
                  <i class="el-icon-arrow-down el-icon--right" />更多
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-permission="['blog:article:manage']">
                    <el-link :undeline="false" type="warning" icon="el-icon-sort-up" @click="handleTop(scope.row.articleId)">置顶</el-link>
                  </el-dropdown-item>
                  <el-dropdown-item v-permission="['blog:article:public']">
                    <el-link :undeline="false" type="warning" icon="el-icon-position" @click="handlePublish(scope.row.articleId)">发布</el-link>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="tableQuery.total>0" :total="tableQuery.total" :page.sync="tableQuery.page" :limit.sync="tableQuery.limit" @pagination="getTableData" />
      </el-card>
    </el-row>

    <el-dialog title="内容爬取" :modal="false" :visible.sync="showCrawlDialog" :fullscreen="true" :before-close="closeDialog">
      <crawl-form ref="crawlForm" />
    </el-dialog>
  </div>
</template>

<script>
import { manageTable, manageFeatured, manageTop, managePublish, manageDelete } from '@/api/tool/craw'
import CrawlForm from './form'

export default {
  components: {
    CrawlForm
  },
  data() {
    return {
      showSearch: true,
      queryData: {
        Q_channel_S_EQ: '',
        Q_title_S_LK: undefined,
        Q_status_S_EQ: '',
        Q_open_S_EQ: '',
        Q_source_S_EQ: 'crawl'
      },
      optionOfChannel: [],
      optionOfPermission: [],
      optionOfStatus: [],
      tableLoading: false,
      tableData: [],
      tableQuery: {
        page: 1,
        limit: 20,
        total: 0,
        sort: undefined,
        order: undefined
      },
      selectionData: [],
      changePerm: false,
      showCrawlDialog: false
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      // 加载下拉菜单
      this.getDictData()
      this.getTableData()
    },
    getDictData() {
      this.changePerm = this.$perm.hasPermissionOr(['blog:article:manage'])
      const that = this
      this.$http.all([this.$dictGroup('blog_article_channel'), this.$dictGroup('blog_article_open'), this.$dictGroup('blog_article_status')])
        .then(this.$http.spread(function(channel, permission, status) {
          that.optionOfChannel = channel
          that.optionOfPermission = permission
          that.optionOfStatus = status
      }))
    },
    getDictType(property, value) {
      return this.getDictElement(property, value)[0]
    },
    getDictValue(property, value) {
      return this.getDictElement(property, value)[1]
    },
    getDictColor(property, value) {
      return this.getDictElement(property, value)[2]
    },
    getDictElement(property, value) {
      if (property === 'channel') {
        return this.$api.getDictElement(this.optionOfChannel, value)
      } else if (property === 'status') {
        return this.$api.getDictElement(this.optionOfStatus, value)
      }
    },
    getImageSrc(value) {
      return this.$api.getImageSrc(value)
    },
    handleFilter() {
      this.tableQuery.page = 1
      this.getTableData()
    },
    handleClear() {
      this.$refs.queryForm.resetFields()
      this.getTableData()
    },
    getTableData() {
      const query = Object.assign(this.tableQuery, this.queryData)
      this.tableLoading = true
      manageTable(query).then(response => {
        this.tableData = response.param.data
        this.tableQuery.total = response.param.recordsTotal
        this.tableLoading = false
        this.$refs.queryTable.bodyWrapper.scrollTop = 0
      }).catch(e => {
        this.tableLoading = false
      })
    },
    sortChange(data) {
      const { prop, order } = data
      this.tableQuery.sort = prop
      if (order === 'ascending') {
        this.tableQuery.order = 'asc'
      } else {
        this.tableQuery.order = 'desc'
      }
      this.getTableData()
    },
    handleSelectionChange(val) {
      this.selectionData = val
    },
    feature(row) {
      const title = row.featured === '0' ? '推荐' : '取消推荐'
      this.$confirm(`是否${title}该文章?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        manageFeatured({
          id: row.articleId,
          featured: row.featured
        }).then(response => {
          this.getTableData()
          this.$modal.msgSuccess(`${title}成功!`)
        }).catch(e => {})
      }).catch(e => {
        row.featured = row.featured === '0' ? '1' : '0'
      })
    },
    handleTop(id) {
      this.$confirm(`是否置顶该文章?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        manageTop({ id: id }).then(response => {
          this.$modal.msgSuccess(`置顶成功!`)
        }).catch(e => {})
      }).catch(e => {})
    },
    handlePublish(id) {
      const ids = this.selectionData.map(row => row.articleId).join(',')

      id = id || ids
      if (!id || id.length === 1) {
        this.$modal.msgWarning('请先选中数据项')
        return
      }

      this.$confirm('是否发布选中的文章?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(() => {
        managePublish({ ids: id }).then(response => {
          this.getTableData()
          this.$modal.msgSuccess('发布成功!')
        }).catch(e => {})
      }).catch(e => {})
    },
    handleGrep() {
      this.showCrawlDialog = true
      this.$nextTick(() => {
        this.$refs.crawlForm.init()
      })
    },
    handleEdit(id) {
      this.showCrawlDialog = true
      this.$nextTick(() => {
        this.$refs.crawlForm.init(id)
      })
    },
    closeDialog(done) {
      this.$refs.crawlForm.onClose()
      done()
      document.body.style.overflow = 'auto'
    },
    handleDelete(id) {
      const ids = this.selectionData.map(function(row, index) {
        return row.articleId
      }).join(',')

      id = id || ids
      if (!id || id.length === 1) {
        this.$modal.msgWarning('请先选中数据项')
        return
      }

      this.$confirm('是否删除所选?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(() => {
        manageDelete({ ids: id }).then(response => {
          this.handleFilter()
          this.$modal.msgSuccess(response.msg)
        }).catch(e => {})
      }).catch(e => {})
    }
  }
}
</script>
